from database.database import Database
import datetime

class ProxyPoolTable(Database):
    def __init__(self):
        self.table_name = "proxy_pool"

    def truncate(self):
        sql = f"truncate table {self.table_name}"
        self.execute(sql)
        
    def clear(self, url):
        sql = f"delete from {self.table_name} where `url` = '{url}'"
        self.execute(sql)
        
    def insert(self, ips, url):
        sql = f"insert into {self.table_name} (`ip`, `url`) values "
        for ip in ips:
            sql += f"('{ip}', '{url}'),"
        sql = sql[:-1]
        self.execute(sql)
        
    def fetchall(self, url):
        sql = f"select `ip` from {self.table_name} where `url` = '{url}'"
        self.execute(sql)
        records = self.cursor.fetchall()
        return [record['ip'] for record in records]
    
    def expired_time(self, url, duration):
        sql = f"select max(`gmt_create`) as `gmt_create` from {self.table_name} where `url` = '{url}'"
        self.execute(sql)
        record = self.cursor.fetchone()
        if not record or not record['gmt_create']:
            return datetime.datetime.now()
        return record['gmt_create'] + datetime.timedelta(seconds=duration)